#pragma once
#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
#define FIFO_FILE "fifo"
#define PATH "."
#define ERR_EXIT(m) do {perror(m); exit(EXIT_FAILURE); } while(0)
class IpcFifo
{
    public:
    IpcFifo(const std::string& path,const std::string &name)
    :_path(path),_name(name)
    {
        _fifoname=_path+"/"+_name;
        umask(0);
        //新建管道
        int n=mkfifo(_fifoname.c_str(),0666);
        if(n!=0){
        std::cerr<<"mkfifo error"<<std::endl;
        }
        else{
            std::cout<<"mkfifo successful"<<std::endl;
        }
    }
    ~IpcFifo(){
       int n=unlink(_fifoname.c_str());
       if(n!=0){
        std::cerr<<"unlink error"<<std::endl;
       }
    }
    private:
        std::string _path;
        std::string _name;
        std::string _fifoname=_path+"/"+_name;
};
class FileOper
{
    public:
    FileOper(const std::string& path,const std::string &name)
     :_path(path),_name(name),_fd(-1)
     {
         _fifoname=_path+"/"+_name;
     }
     ~FileOper(){}
    void OpenForRead(){
         _fd=open(_fifoname.c_str(),O_RDONLY);
        if(_fd<0){
            std::cerr<<"open error"<<std::endl;
        }
        else{
            std::cout<<"open successful"<<std::endl;
        }
    }
    void OpenForWrite(){
        _fd=open(_fifoname.c_str(),O_WRONLY);
        if(_fd<0){
            std::cerr<<"open error"<<std::endl;
        }
        else{
            std::cout<<"open successful"<<std::endl;
        }
    }
    void Wakeup(){
        char x='c';
         int n = write(_fd, &x, 1);
        if (n > 0)
        {
            std::cout << "send sucessful" << std::endl;
        }
    }
    bool Read(){
       char c;
       int n=read(_fd,&c,1);
      if(n>0)return true;
      return false;
    }
    void Close(){
        if(_fd>0){
            close(_fd);
        }
    }
    private:
      std::string _path;
      std::string _name;
      std::string _fifoname;  
      int _fd;
};